package jnpf.controller;


import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.NoDataSourceBind;
import jnpf.base.UserInfo;
import jnpf.base.entity.DictionaryDataEntity;
import jnpf.base.service.DictionaryDataService;
import jnpf.base.util.OptimizeUtil;
import jnpf.base.vo.DownloadVO;
import jnpf.base.vo.ListVO;
import jnpf.config.ConfigValueUtil;
import jnpf.exception.DataException;
import jnpf.model.LanguageVO;
import jnpf.model.UploaderVO;
import jnpf.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * 通用控制器
 */
@Api(tags = "公共", value = "file")
@RestController
@RequestMapping("/api/file")
public class UtilsController {

    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private DictionaryDataService dictionaryDataService;

    /**
     * 语言列表
     *
     * @return
     */
    @ApiOperation("语言列表")
    @GetMapping("/Language")
    public ActionResult<ListVO<LanguageVO>> getList() {
        String dictionaryTypeId = "dc6b2542d94b407cac61ec1d59592901";
        List<DictionaryDataEntity> list = dictionaryDataService.getList(dictionaryTypeId);
        List<LanguageVO> language = JsonUtil.getJsonToList(list, LanguageVO.class);
        ListVO vo = new ListVO();
        vo.setList(language);
        return ActionResult.success(vo);
    }

    /**
     * 图形验证码
     *
     * @return
     */
    @NoDataSourceBind()
    @ApiOperation("图形验证码")
    @GetMapping("/ImageCode/{timestamp}")
    public void imageCode(@PathVariable("timestamp") String timestamp) {
        DownUtil.downCode();
        redisUtil.insert(timestamp, ServletUtil.getSession().getAttribute(CodeUtil.RANDOMCODEKEY), 120);
    }

    /**
     * 上传文件/图片
     *
     * @return
     */
    @NoDataSourceBind()
    @ApiOperation("上传文件/图片")
    @PostMapping(value = "/Uploader/{type}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ActionResult uploader(@RequestPart("file") MultipartFile file, @PathVariable("type") String type) {
        String fileType = UpUtil.getFileType(file);
        //验证类型
        if ("weixin".equals(type)) {
            if (!OptimizeUtil.fileType(configValueUtil.getWeChatUploadFileType(), fileType) && !OptimizeUtil.fileType(configValueUtil.getMpUploadFileType(), fileType)) {
                return ActionResult.fail("上传失败，文件格式不允许上传");
            }
            if (OptimizeUtil.fileSize(file.getSize(), 1024000)) {
                return ActionResult.fail("上传失败，文件大小超过1M");
            }
        } else {
            if (!OptimizeUtil.fileType(configValueUtil.getAllowUploadFileType(), fileType)) {
                return ActionResult.fail("上传失败，文件格式不允许上传");
            }
            if (OptimizeUtil.fileSize(file.getSize(), 1024000)) {
                return ActionResult.fail("上传失败，文件大小超过1M");
            }
        }
        String fileName = DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + "." + fileType;
        UploaderVO vo = UploaderVO.builder().name(fileName).build();
        String filePath = null;
        if ("userAvatar".equals(type)) {
            filePath = configValueUtil.getUserAvatarFilePath();
            vo.setUrl(UploaderUtil.uploaderImg(fileName));
        } else if ("mail".equals(type)) {
            filePath = configValueUtil.getEmailFilePath();
        } else if ("IM".equals(type)) {
            filePath = configValueUtil.getImContentFilePath();
        } else if ("weixin".equals(type)) {
            filePath = configValueUtil.getTemporaryFilePath();
        } else if ("workFlow".equals(type)) {
            filePath = configValueUtil.getTemporaryFilePath();
        } else if ("annex".equals(type)) {
            filePath = configValueUtil.getWebAnnexFilePath();
            UserInfo userInfo = userProvider.get();
            vo.setUrl(UploaderUtil.uploaderFile("/api/file/Download/", userInfo.getId() + "#" + fileName));
        } else if ("annexpic".equals(type)) {
            filePath = configValueUtil.getWebAnnexFilePath();
            vo.setUrl(UploaderUtil.uploaderImg("/api/file/Image/annex/", fileName));
        }
        FileUtil.upFile(file, filePath, fileName);
        return ActionResult.success(vo);
    }

    /**
     * 获取下载文件链接
     *
     * @return
     */
    @NoDataSourceBind()
    @ApiOperation("获取下载文件链接")
    @GetMapping("/Download/{type}/{fileName}")
    public ActionResult<DownloadVO> downloadUrl(@PathVariable("type") String type, @PathVariable("fileName") String fileName) {
        UserInfo userInfo = userProvider.get();
        String filePath = null;
        if ("userAvatar".equals(type)) {
            filePath = configValueUtil.getUserAvatarFilePath() + fileName;
        } else if ("mail".equals(type)) {
            filePath = configValueUtil.getEmailFilePath() + fileName;
        } else if ("IM".equals(type)) {
            filePath = configValueUtil.getImContentFilePath() + fileName;
        } else if ("weixin".equals(type)) {
            filePath = configValueUtil.getMpMaterialFilePath() + fileName;
        } else if ("workFlow".equals(type)) {
            filePath = configValueUtil.getSystemFilePath() + fileName;
        } else if ("dataBackup".equals(type)) {
            filePath = configValueUtil.getDataBackupFilePath() + fileName;
        } else if ("annex".equals(type)) {
            filePath = configValueUtil.getWebAnnexFilePath() + fileName;
        }
        if (FileUtil.fileIsFile(filePath)) {
            DownloadVO vo = DownloadVO.builder().name(fileName).url(UploaderUtil.uploaderFile(userInfo.getId() + "#" + fileName + "#" + type)).build();
            return ActionResult.success(vo);
        }
        return ActionResult.fail("文件不存在");
    }

    /**
     * 下载文件链接
     *
     * @return
     */
    @NoDataSourceBind()
    @ApiOperation("下载文件链接")
    @GetMapping("/Download")
    public void downloadFile() throws DataException {
        HttpServletRequest request = ServletUtil.getRequest();
        String reqJson = request.getParameter("encryption");
        String fileNameAll = DesUtil.aesDecode(reqJson);
        if (!StringUtil.isEmpty(fileNameAll)) {
            String[] data = fileNameAll.split("#");
            String token = data.length > 0 ? data[0] : "";
            if (redisUtil.exists(token)) {
                String fileName = data.length > 1 ? data[1] : "";
                String filePath = configValueUtil.getTemporaryFilePath() + fileName;
                String type = data.length > 2 ? data[2] : "";
                if ("userAvatar".equals(type)) {
                    filePath = configValueUtil.getUserAvatarFilePath() + fileName;
                } else if ("mail".equals(type)) {
                    filePath = configValueUtil.getEmailFilePath() + fileName;
                } else if ("IM".equals(type)) {
                    filePath = configValueUtil.getImContentFilePath() + fileName;
                } else if ("weixin".equals(type)) {
                    filePath = configValueUtil.getMpMaterialFilePath() + fileName;
                } else if ("workFlow".equals(type)) {
                    filePath = configValueUtil.getSystemFilePath() + fileName;
                } else if ("dataBackup".equals(type)) {
                    filePath = configValueUtil.getDataBackupFilePath() + fileName;
                } else if ("annex".equals(type)) {
                    filePath = configValueUtil.getWebAnnexFilePath() + fileName;
                } else if ("document".equals(type)) {
                    filePath = configValueUtil.getDocumentFilePath() + fileName;
                } else if ("preview".equals(type)) {
                    filePath = configValueUtil.getDocumentPreviewPath() + fileName;
                }
                if (FileUtil.fileIsFile(filePath)) {
                    if (FileUtil.fileIsFile(filePath)) {
                        if (!DownUtil.dowloadFile(filePath, fileName)) {
                            throw new DataException("文件不存在");
                        }
                    }
                } else {
                    throw new DataException("文件不存在");
                }
            } else {
                throw new DataException("token验证失败");
            }
        }
    }

    /**
     * 下载文件链接
     *
     * @return
     */
    @NoDataSourceBind()
    @ApiOperation("下载模板文件链接")
    @GetMapping("/DownloadModel")
    public void downloadModel() throws DataException {
        HttpServletRequest request = ServletUtil.getRequest();
        String reqJson = request.getParameter("encryption");
        String fileNameAll = DesUtil.aesDecode(reqJson);
        if (!StringUtil.isEmpty(fileNameAll)) {
            String token = fileNameAll.split("#")[0];
            if (redisUtil.exists(token)) {
                String fileName = fileNameAll.split("#")[1];
                String filePath = configValueUtil.getTemplateFilePath() + fileName;
                if (FileUtil.fileIsFile(filePath)) {
                    if (!DownUtil.dowloadFile(filePath, fileName)) {
                        throw new DataException("下载失败");
                    }
                }
            }
        }
    }


    /**
     * 获取图片
     *
     * @param fileName
     * @param type
     * @return
     */
    @NoDataSourceBind()
    @ApiOperation("获取图片")
    @GetMapping("/Image/{type}/{fileName}")
    public void downLoadImg(@PathVariable("type") String type, @PathVariable("fileName") String fileName) {
        String filePath = "";
        if ("userAvatar".equals(type)) {
            filePath = configValueUtil.getUserAvatarFilePath() + fileName;
        } else if ("mail".equals(type)) {
            filePath = configValueUtil.getEmailFilePath() + fileName;
        } else if ("IM".equals(type)) {
            filePath = configValueUtil.getImContentFilePath() + fileName;
        } else if ("weixin".equals(type)) {
            filePath = configValueUtil.getMpMaterialFilePath() + fileName;
        } else if ("workFlow".equals(type)) {
            filePath = configValueUtil.getSystemFilePath() + fileName;
        } else if ("annex".equals(type)) {
            filePath = configValueUtil.getWebAnnexFilePath() + fileName;
        }
        File file = new File(filePath);
        if (file.exists()) {
            DownUtil.dowloadFile(filePath);
        }
    }

    /**
     * 获取IM聊天图片
     * 注意 后缀名前端故意把 .替换@
     *
     * @param fileName
     * @return
     */
    @NoDataSourceBind()
    @ApiOperation("获取IM聊天图片")
    @GetMapping("/IMImage/{fileName}")
    public void imImage(@PathVariable("fileName") String fileName) {
        String paths = configValueUtil.getImContentFilePath() + fileName;
        File file = new File(paths);
        if (file.exists()) {
            DownUtil.dowloadFile(paths);
        }
    }

    /**
     * 获取IM聊天语音
     * 注意 后缀名前端故意把 .替换@
     *
     * @param fileName
     * @return
     */
    @NoDataSourceBind()
    @ApiOperation("获取IM聊天语音")
    @GetMapping("/IMVoice/{fileName}")
    public void imVoice(@PathVariable("fileName") String fileName) {
        String paths = configValueUtil.getImContentFilePath() + fileName.replaceAll("@", ".");
        File file = new File(paths);
        if (file.exists()) {
            DownUtil.dowloadFile(paths);
        }
    }

    /**
     * app启动获取信息
     *
     * @param appName
     * @return
     */
    @NoDataSourceBind()
    @ApiOperation("app启动获取信息")
    @GetMapping("/AppStartInfo/{appName}")
    public ActionResult getAppStartInfo(@PathVariable("appName") String appName) {
        JSONObject object = new JSONObject();
        object.put("AppVersion", configValueUtil.getAppVersion());
        object.put("AppUpdateContent", configValueUtil.getAppUpdateContent());
        return ActionResult.success(object);
    }
}
